package cn.dida.controller;

import cn.dida.exception.BizzException;
import cn.dida.model.*;
import cn.dida.service.ProductService;
import cn.dida.service.SalesmanPayruleService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by zhangzhiling on 2017/8/30.
 */
@Controller
@RequestMapping("/salemanPayrule")
public class SalesmanPayruleController extends BaseController {

    @Autowired
    private SalesmanPayruleService payruleService;

    @Autowired
    private ProductService productService;

    /**
     * 分页列表
     * @param request
     * @param response
     * @param name
     * @param state
     * @param adcode
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/list")
    public ModelAndView salepaymentyList(HttpServletRequest request, HttpServletResponse response, String name, Integer state,String adcode, Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
//        Map<String, Object> paramMap = getSimpleRequestParamMap(request);
        page = (page == null || page < 1) ? 1 : page;
        name = StringUtils.trimToNull(name);
        adcode = StringUtils.trimToNull(adcode);
        Pageable<SalesmanPayrule> pagelist = payruleService.queryList(userSession.getCompanyId(), name, adcode, state, page);

        model.put("pagelist", pagelist);
        model.put("name", name);
        model.put("state", state);
        return new ModelAndView("salesman_payrule_list").addAllObjects(model);
    }

    /**
     * 数据导出列表
     * @param request
     * @param response
     * @param name
     * @param state
     * @return
     * @throws Exception
     */
    @GetMapping("/export")
    public ModelAndView branch_export(HttpServletRequest request, HttpServletResponse response,  String name, Integer state) throws Exception {
        UserSession userSession = getUserSession(request);

        List<SalesmanPayrule> exportList = payruleService.exportList(userSession.getCompanyId(), name, state);

        String fileName = "结算规则数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (SalesmanPayrule obj : exportList) {
            fmap = new HashMap<String, Object>();
            fmap.put("id", obj.getId());
            fmap.put("name", obj.getName());
            String time = DateUtils.transferLongToDate("yyyy-MM-dd", obj.getValid_begin_time())+"至"+
                    DateUtils.transferLongToDate("yyyy-MM-dd", obj.getValid_end_time());
            fmap.put("time", time);
            Integer sta = obj.getState();
            if (sta == 0) {
                fmap.put("state", "未启用");
            } else if (sta == 1) {
                fmap.put("state", "使用中");
            }else if (sta == 2) {
                fmap.put("state", "已失效");
            }else{
                fmap.put("state", "已停用");
            }
            fmap.put("c_time",DateUtils.transferLongToDate("yyyy-MM-dd", obj.getC_time()));
            fmap.put("account", obj.getAccount());
            list.add(fmap);
        }


        String columnNames[] = {"ID", "规则名称", "时间", "当前状态",  "创建时间", "创建人"};//列名
        String keys[] = {"id", "name", "time", "state", "c_time", "account"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }

    /**
     * 打开新建单据页面
     * @param request
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("/add")
    public ModelAndView add(HttpServletRequest request, HttpSession session) throws Exception {
        UserSession userSession = getUserSession(request);
        Map<String, Object> model = new HashMap<String, Object>();

        Pageable<Product> productList = productService.queryProduct(userSession.getCompanyId(), "", 1, 1);
        model.put("productList", productList);
        return new ModelAndView("salesman_payrule_new").addAllObjects(model);
    }

    /**
     * 添加
     * @param request
     * @param payrule
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/add_submit")
    public HttpResponseBodyWrapper add(HttpServletRequest request, @RequestBody SalesmanPayrule payrule) throws Exception {


        UserSession userSession = getUserSession(request);
        payrule.setCompany_id(userSession.getCompanyId());
        payrule.setStaff_id(userSession.getId());

//        Boolean flag = lgsBillService.isExistsBillNo(userSession.getCompanyId(), lgsBills.getBillsNo(),1);
//        if(flag){
//            throw new BizzException(BizzException.error_code_invalid_params, "已存在【"+lgsBills.getBillsNo()+"】的单据");
//        }

//        lgsBills.setBillsNo(StringUtils.trimToNull(lgsBills.getBillsNo()));
        Integer  result= payruleService.insertPayrule(payrule );
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 查看页面
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/getdetail")
    public ModelAndView detail(HttpServletRequest request, Integer id) throws Exception {
        UserSession userSession = getUserSession(request);
        Map<String, Object> model = new HashMap<String, Object>();
        if(id== null){
            throw new BizzException(BizzException.error_code_invalid_params, "操作出错，请重新操作！");
        }

        SalesmanPayrule salesmanPayrule = payruleService.getDetail(id);
        model.put("payrule", salesmanPayrule);
        return new ModelAndView("salesman_payrule_detail").addAllObjects(model);
    }


    @ResponseBody
    @PostMapping("/updateStateTest")
    public HttpResponseBodyWrapper test(HttpServletRequest request, Integer id) throws Exception {


        if(id== null ){
            throw new BizzException(BizzException.error_code_invalid_params, "操作出错，请重新操作！");
        }
        Boolean  result= payruleService.test(id);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 启用、停用
     * @param request
     * @param id
     * @param state 1,。启用，3.停用
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/updateState")
    public HttpResponseBodyWrapper updateState(HttpServletRequest request, Integer id, Integer state) throws Exception {


        if(id== null || state == null || (state !=1 && state !=3 )){
            throw new BizzException(BizzException.error_code_invalid_params, "操作出错，请重新操作！");
        }
        Integer  result= payruleService.updateState(id,state );
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 进入编辑页面
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/edit")
    public ModelAndView edit(HttpServletRequest request, Integer id) throws Exception {
        UserSession userSession = getUserSession(request);
        Map<String, Object> model = new HashMap<String, Object>();
        if(id== null){
            throw new BizzException(BizzException.error_code_invalid_params, "操作出错，请重新操作！");
        }

        SalesmanPayrule salesmanPayrule = payruleService.getDetail(id);
        model.put("payrule", salesmanPayrule);

        Pageable<Product> productList = productService.queryProduct(userSession.getCompanyId(), "", 1, 1);
        model.put("productList", productList);
        return new ModelAndView("salesman_payrule_edit").addAllObjects(model);
    }

    /**
     * 更新
     * @param request
     * @param payrule
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/edit_submit")
    public HttpResponseBodyWrapper edit_submit(HttpServletRequest request, @RequestBody SalesmanPayrule payrule) throws Exception {


        UserSession userSession = getUserSession(request);
        payrule.setCompany_id(userSession.getCompanyId());
        payrule.setStaff_id(userSession.getId());
        Integer  result= payruleService.updatePayrule(payrule);
        if(result != 1){
            throw new BizzException(BizzException.error_code_invalid_params, "操作出错，请重新操作！");
        }
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 适用区域产品详情 列表
     * @param adcode
     * @param prodct
     * @param baseId
     * @param page
     * @return
             */
    @PostMapping("/getProdAndAreaList")
    @ResponseBody
    public HttpResponseBodyWrapper getProdAndAreaList(HttpServletRequest request, String adcode,String prodct, String area, String baseId,Integer state,Integer page) throws Exception {


        if(adcode== null || adcode=="" || baseId == null || baseId ==""){
            throw new BizzException(BizzException.error_code_invalid_params, "操作出错，请重新操作！");
        }
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        //Pageable<Product> selectedProductList = activityService.querySelected(userSession.getCompanyId(), keyword, 1, page);
        if(prodct != null){
            prodct=prodct.trim();
        }
        if(area != null){
            area=area.trim();
        }
        Pageable<Map<String,Object>> pageList = payruleService.getProdAndAreaList(adcode, prodct,area, baseId,state, page);

        return new HttpResponseBodyWrapper(pageList);
    }

    /**
     * 规则查询 列表
     * @param request
     * @param prodct
     * @param area
     * @param state
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/searchList")
    public ModelAndView payruleSearchList(HttpServletRequest request,String prodct, String area,Integer state,Integer page) throws Exception {

        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
//        Map<String, Object> paramMap = getSimpleRequestParamMap(request);
        page = (page == null || page < 1) ? 1 : page;
        prodct = StringUtils.trimToNull(prodct);
        area = StringUtils.trimToNull(area);
        Pageable<Map<String, Object>> pagelist = payruleService.payruleSearchList(userSession.getCompanyId(), prodct, area, state, page);

        model.put("pagelist", pagelist);
        model.put("prodct", prodct);
        model.put("area", area);
        model.put("state", state);
        return new ModelAndView("salesman_payrule_list_search").addAllObjects(model);
    }

    @GetMapping("/searchList_export")
    public ModelAndView searchList_export(HttpServletRequest request, HttpServletResponse response ,String prodct, String area,Integer state) throws Exception {
        UserSession userSession = getUserSession(request);

        List<Map<String,Object>> exportList = payruleService.searchList_export(userSession.getCompanyId(), prodct,area, state);

        String fileName = "规则查询数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (Map<String,Object> obj : exportList) {
            fmap = new HashMap<String, Object>();
            fmap.put("proName", obj.get("proName"));
            fmap.put("adname", obj.get("adname"));
            String time = DateUtils.transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long)obj.get("valid_begin_time"))+"至"+
                    DateUtils.transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long)obj.get("valid_end_time"));
            fmap.put("time", time);
            fmap.put("day_limit",obj.get("day_limit"));
            Integer pay_condition = (Integer)obj.get("pay_condition");
            if(pay_condition == 1){
                fmap.put("pay_limit",(BigDecimal)obj.get("pay_limit") + "瓶");
            }else{
                fmap.put("pay_limit","￥" + (BigDecimal)obj.get("pay_limit"));
            }
            fmap.put("name", obj.get("name"));
            Integer sta = (Integer) obj.get("state");
            if (sta == 0) {
                fmap.put("state", "未启用");
            } else if (sta == 1) {
                fmap.put("state", "正常");
            }else {
                fmap.put("state", "封存");
            }

            list.add(fmap);
        }


        String columnNames[] = {"产品", "区域", "有效时间", "每日提现次数",  "提现条件", "规则", "状态"};//列名
        String keys[] = {"proName", "adname", "time", "day_limit", "pay_limit", "name","state"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }

}
